import React, { useState, useEffect } from "react";
import { Form, Input, Modal, Space, Button, message } from "antd";
import { get, post } from '../../service/axiosManager'; // 导入 get 和 post 函数
import { LockOutlined, LockTwoTone, SafetyCertificateOutlined, SafetyCertificateTwoTone, UserOutlined } from "@ant-design/icons";
import './login.css';

export default function LoginFrom({ open, setOpen,firmName }: { open: boolean; setOpen: (open: boolean) => void;firmName:string }) {
    const [captchaSrc, setCaptchaSrc] = useState("");
    const [form] = Form.useForm(); // 使用 Form.useForm() 获取表单实例
    const [codeKey, setCodeKey] = useState(`${1629428467008}`);

    useEffect(() => {
        fetchCaptcha();
    }, []);

    const fetchCaptcha = async () => {
        try {
            const response = await get('/sys/randomImage/' + codeKey, {}, false); // 使用 get 函数请求验证码
            setCaptchaSrc(response.result);
        } catch (error) {
            console.error("获取验证码失败", error);
        }
    };

    const onFinish = async (values: any) => {
        try {
            values.checkKey = codeKey;
            const response = await post('/sys/login', values, false);
            if (response.code === 200) {
                console.log('登录成功:', response);
                localStorage.setItem('token', response.result.token);
                localStorage.setItem('userInfo', JSON.stringify(response.result.userInfo));
                setOpen(false);
                window.location.reload();
            } else {
                console.error('登录失败:', response);
                message.error('登录失败:' + response.message);
            }
        } catch (error) {
            console.error('登录失败:', error);
        }
    };

    return (
        <Modal
            centered
            closable={false}
            open={open}
            footer={[
                <Button type="primary" style={{width: 360, textAlign: 'center', padding: '20px 20px'}} onClick={() => {
                    form.validateFields().then(values => {
                        onFinish(values); // 传入表单数据
                    }).catch(info => {
                        console.error('验证失败:', info);
                        message.error('验证失败');
                    });
                }}>登录</Button>
            ]}
            onCancel={() => setOpen(false)}
            width={400}
        >
            <div style={{display: 'flex', justifyContent: 'center', marginBottom:10}}>
                <img src='/logo.png' alt="logo" style={{width: 30, height: 38}} />
                <span style={{fontSize: 20, marginLeft: 10, fontWeight: 'bold'}}>TSLM</span>
            </div>
            <div style={{display: 'flex', justifyContent: 'center', marginBottom:30}}>
                <span style={{fontSize: 20, color: '#999'}}>{firmName}</span>
            </div>
            {/* <div style={{
                display: 'flex', 
                justifyContent: 'center', 
                marginBottom:30
                }}>
                <span style={{fontSize: 20, color: '#000',borderBottom: '4px solid #1b90ff'}}>登录</span>
            </div> */}
            <Form
                form={form} // 绑定表单实例
                name="complex-form"
                onFinish={onFinish}
                labelCol={{ span: 8 }}
                wrapperCol={{ span: 16 }}
                style={{ maxWidth: 600 }}
            >
                <Form.Item>
                    <Space>
                        <Form.Item
                            name="username"
                            noStyle
                            rules={[{ required: true, message: '用户名不能为空' }]}
                        >
                            <Input addonBefore={<UserOutlined />} variant="borderless" className="input-style" style={{ width: 360}} placeholder="请输入用户名" />
                        </Form.Item>
                    </Space>
                </Form.Item>
                <Form.Item>
                    <Space>
                        <Form.Item
                            name="password"
                            noStyle
                            rules={[{ required: true, message: '密码不能为空' }]}
                        >
                            <Input addonBefore={<LockOutlined />} variant="borderless" className="input-style" style={{ width: 360 }} type="password" placeholder="请输入密码" />
                        </Form.Item>
                    </Space>
                </Form.Item>
                <Form.Item>
                    <Space>
                        <Form.Item
                            name="captcha"
                            noStyle
                            rules={[{ required: true, message: '验证码不能为空' }]}
                        >
                            <Input 
                                addonBefore={<SafetyCertificateOutlined />}
                                addonAfter={<img
                                    src={captchaSrc}
                                    alt="验证码"
                                    style={{ width: 105, height: 35 }}
                                    onClick={fetchCaptcha}
                                />}
                                variant="borderless" 
                                className="captcha-style"
                                style={{ width: 360 }} 
                                placeholder="请输入验证码" 
                                onPressEnter={() => {
                                    form.validateFields().then(values => {
                                        onFinish(values); // 传入表单数据
                                    }).catch(info => {
                                        console.error('验证失败:', info);
                                        message.error('验证失败');
                                    });
                                }}
                            />
                        </Form.Item>
                        <img
                            src={captchaSrc}
                            alt="验证码"
                            style={{ width: 100, height: 40 }}
                            onClick={fetchCaptcha}
                        />
                    </Space>
                </Form.Item>
            </Form>
        </Modal>
    );
}